from cmath import *
from numpy import array, linspace, logspace, pi, log, sin, log10, sqrt, vstack, hstack, transpose, abs
from scipy.interpolate import splprep, splrep, splev
import os,re

j= complex(0,1)
mu = 4.0e-7*pi
ep = 8.854e-12
freqpt = re.compile(r"^# (.*?) .* ([.0-9]+)")

from numpy import exp
def pol(a,b=None):
    "generate complex number from (mag,deg) form"
    if type(a)==type(list()):
        return a[0]*exp(complex(0,1)*a[1]*pi/180)
    return a*exp(complex(0,1)*b*pi/180)

def arg(a):
    "return the argument(in degree) of complex number"
    if abs(a)==0: return 0
    return ((log(a/abs(a))/complex(0,1)).real)*180/pi

def aa(a):
    "return both the amplitude and the argument"
    return [abs(a), arg(a)]
def sp(name,AmpArgMode=False):
    """read S parameters from s2p file"""
    try:
        fin = open(name, 'rb')
        dt = fin.read()
        fin.close()
    except:
        print "file '%s' not found in path %s\nUse direct input...\n"%(name, os.getcwd())
        dt = raw_input()
        name = "rawinput_"
    lines = dt.splitlines()
    scale,z0 = 1.0,50.0
    mat = []
    head = ""
    for i in range(len(lines)):
        line=lines[i].strip()
        if line.startswith("!"):
            head += line+"\n"
            continue
        if line.startswith("#"):
            freqmt = freqpt.findall(line)
            if freqmt:
                freqtext,z0=freqmt[0]
                z0 = float(z0)
                if freqtext.upper().startswith("K"):
                    scale=1e3
                elif freqtext.upper().startswith("M"):
                    scale=1e6
                elif freqtext.upper().startswith("G"):                    
                    scale=1e9
                elif freqtext.upper().startswith("T"):
                    scale=1e12
                print "frequency in (%E)Hz\n"%scale
            head += line+"\n"
            continue
        data=[float(x) for x in line.split()]
        freq, data = data[0]*scale,data[1:]
        if len(data)!=8:
            print 'wrong line: %s'%line
            head += line+"\n"
            continue
        else:
            if AmpArgMode:
                s11,s12,s21,s22 = pol(data[0],data[1]),pol(data[2],data[3]),pol(data[4],data[5]),pol(data[6],data[7])
            else:
                s11,s12,s21,s22 = complex(data[0],data[1]),complex(data[2],data[3]),complex(data[4],data[5]),complex(data[6],data[7])
        mat.append((freq,s11,s12,s21,s22))
    return array(mat),head
def RItoAA(name):
    spmap,head = sp(name, AmpArgMode=False)
    outfile = open(name+"_AA.s2p",'wb')
    outfile.write(head)
    for i in range(len(spmap)):
        outfile.write("%.0f\t%.6E\t%.6E\t%.6E\t%.6E\t%.6E\t%.6E\t%.6E\t%.6E\n"%(spmap[i,0],
                                                                              abs(spmap[i,1]),arg(spmap[i,1])*pi/180,
                                                                              abs(spmap[i,2]),arg(spmap[i,2])*pi/180,
                                                                              abs(spmap[i,3]),arg(spmap[i,3])*pi/180,
                                                                              abs(spmap[i,4]),arg(spmap[i,4])*pi/180))
    outfile.close()
def AAtoRI(name):
    spmap,head = sp(name, AmpArgMode=True)
    outfile = open(name+"_RI.s2p",'wb')
    outfile.write(head)    
    for i in range(len(spmap)):
        outfile.write("%.0f\t%.6E\t%.6E\t%.6E\t%.6E\t%.6E\t%.6E\t%.6E\t%.6E\n"%(spmap[i,0],
                                                                              spmap[i,1].real,spmap[i,1].imag,
                                                                              spmap[i,2].real,spmap[i,2].imag,
                                                                              spmap[i,3].real,spmap[i,3].imag,
                                                                              spmap[i,4].real,spmap[i,4].imag))
    outfile.close()
